<?php 
class Common {

    public static function getValue($value, $array) {
        return $array[$value];
    }

	/**
	 * Debug
	 * 
	 */
	public static function debug($var) {
		echo '<pre style="text-align: left;font-size: 14;">';
		$trace = debug_backtrace();
		echo 'Line: '.$trace[0]['line'].'<br>';
		print_r($var);
		echo '</pre>';
	}
	
	/**
	 * Debug then die
	 * 
	 */
	public static function debugdie($var) {
		echo '<pre style="text-align: left;font-size: 14;">';
		$trace = debug_backtrace();
		echo 'Line: '.$trace[0]['line'].'<br>';
		print_r($var);
		echo '</pre>';
		die();
	}

    /**
     * @param $emailAdd string|array email address
     * @param $subject string subject
     * @param $content string content email
     * @return bool
     */
    public static function sentMail($emailAdd, $subject, $content){
        //Sent mail login info
        Yii::import('application.extensions.phpmailer.JPhpMailer');
        $mail = new SmtpMailer();
        $mail->IsSMTP();
        $mail->SetFrom(SystemConfig::MAIL_ACCOUNT, SystemConfig::MAIL_NAME);

        $mail->Subject = $subject;
        $mail->MsgHTML($content);
        if(is_array($emailAdd)){
            foreach($emailAdd as $add){
                $mail->AddBCC($add);
            }
        }else{
            $mail->AddAddress($emailAdd);
        }

        if ($mail->Send()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Sanitize data which will be injected into SQL query
     *
     * @param string $string SQL data which will be injected into SQL query
     * @param boolean $htmlOK Does data contain HTML code ? (optional)
     * @return string Sanitized data
     */
    public static function pSQL($string, $htmlOK = false)
    {
        if (get_magic_quotes_gpc())
            $string = stripslashes($string);

        if (!is_numeric($string))
        {
            $string = function_exists('mysql_real_escape_string') ? mysql_real_escape_string($string) : addslashes($string);
            if (!$htmlOK)
                $string = strip_tags(nl2br($string));
        }

        return $string;
    }

    /**
     * @param $deadline datetime
     * @return bool
     */
    public static function compareDeadline($deadline){
        $dateNow = date('Y-m-d');
        $deadline = date('Y-m-d', strtotime($deadline));
        $dateEnd = date('Y-m-d', strtotime($dateNow . '+2 day'));
        if(strtotime($deadline) <= strtotime($dateEnd) && strtotime($deadline) >= strtotime($dateNow)){
            return true;
        }
        return false;

    }

    public static function formatDate($datetime=null){
        if(is_null($datetime)){
            return date(Constant::FORMAT_DATE);
        }else{
            return date(Constant::FORMAT_DATE, strtotime($datetime));
        }

    }

    public static function getStatusShip($status = null){
        $result = array(
            Constant::STATUS_SHIP_PENDING => Yii::t('app', 'Shipping'),
            Constant::STATUS_SHIP_SHIPED => Yii::t('app', 'Shiped'),
            Constant::STATUS_SHIP_CANCEL => Yii::t('app', 'Cancel'),
        );
        if(!is_null($status)){
            return (isset($result[$status]) ? $result[$status] : Yii::t('app', 'No status'));
        }
        return $result;

    }

    /**
     * generate Signature transporter to image
     *
     * @param null $name
     * @param string $id_transporter
     */
    public static function _generateSignature($name=null, $id_transporter = 'id'){
        if(is_null($name)){
            return;
        }
        $img = imagecreatetruecolor(250, 30);
        $bgColour = imagecolorallocate($img, 0xff, 0xff, 0xff);
        $penColour = imagecolorallocate($img, 0x14, 0x53, 0x94);
        imagefilledrectangle($img, 0, 0, 399, 29, $bgColour);
        $font = 'signature/journal.ttf';
        imagettftext($img, 20, 0, 10, 20, $penColour, $font, $name);
        imagepng($img, 'signature/'.$id_transporter.'.png');
        imagedestroy($img);
    }


    /**
     *  Accepts a signature created by signature pad in Json format
     *  Converts it to an image resource
     *  The image resource can then be changed into png, jpg whatever PHP GD supports
     *
     *  To create a nicely anti-aliased graphic the signature is drawn 12 times it's original size then shrunken
     *
     *  @param string|array $json
     *  @param array $options OPTIONAL; the options for image creation
     *    imageSize => array(width, height)
     *    bgColour => array(red, green, blue) | transparent
     *    penWidth => int
     *    penColour => array(red, green, blue)
     *    drawMultiplier => int
     *
     *  @return object
     */
    public static function sigJsonToImage ($json, $options = array()) {
        $defaultOptions = array(
            'file_name' => 'id_transporter',
            'imageSize' => array(Constant::IMG_WIDTH_SIGNATURE, Constant::IMG_HEIGHT_SIGNATURE),
            'bgColour' => array(0xff, 0xff, 0xff),
            'penWidth' => 2,
            'penColour' => array(0x14, 0x53, 0x94),
            'drawMultiplier'=> 12
        );

        $options = array_merge($defaultOptions, $options);

        $img = imagecreatetruecolor($options['imageSize'][0] * $options['drawMultiplier'], $options['imageSize'][1] * $options['drawMultiplier']);

        if ($options['bgColour'] == 'transparent') {
            imagesavealpha($img, true);
            $bg = imagecolorallocatealpha($img, 0, 0, 0, 127);
        } else {
            $bg = imagecolorallocate($img, $options['bgColour'][0], $options['bgColour'][1], $options['bgColour'][2]);
        }

        $pen = imagecolorallocate($img, $options['penColour'][0], $options['penColour'][1], $options['penColour'][2]);
        imagefill($img, 0, 0, $bg);

        if (is_string($json))
            $json = json_decode(stripslashes($json));

        foreach ($json as $v)
            self::drawThickLine($img, $v->lx * $options['drawMultiplier'], $v->ly * $options['drawMultiplier'], $v->mx * $options['drawMultiplier'], $v->my * $options['drawMultiplier'], $pen, $options['penWidth'] * ($options['drawMultiplier'] / 2));

        $imgDest = imagecreatetruecolor($options['imageSize'][0], $options['imageSize'][1]);

        if ($options['bgColour'] == 'transparent') {
            imagealphablending($imgDest, false);
            imagesavealpha($imgDest, true);
        }

        imagecopyresampled($imgDest, $img, 0, 0, 0, 0, $options['imageSize'][0], $options['imageSize'][0], $options['imageSize'][0] * $options['drawMultiplier'], $options['imageSize'][0] * $options['drawMultiplier']);

        $srcImage = 'signature'.DIRECTORY_SEPARATOR.($options['file_name'] ? $options['file_name'] : 'id_transporter').'.png';
        imagepng($img, $srcImage);
        imagedestroy($imgDest);
        imagedestroy($img);
        return $srcImage;
    }

    /**
     *  Draws a thick line
     *  Changing the thickness of a line using imagesetthickness doesn't produce as nice of result
     *
     *  @param object $img
     *  @param int $startX
     *  @param int $startY
     *  @param int $endX
     *  @param int $endY
     *  @param object $colour
     *  @param int $thickness
     *
     *  @return void
     */
    public static function drawThickLine ($img, $startX, $startY, $endX, $endY, $colour, $thickness) {
        $angle = (atan2(($startY - $endY), ($endX - $startX)));

        $dist_x = $thickness * (sin($angle));
        $dist_y = $thickness * (cos($angle));

        $p1x = ceil(($startX + $dist_x));
        $p1y = ceil(($startY + $dist_y));
        $p2x = ceil(($endX + $dist_x));
        $p2y = ceil(($endY + $dist_y));
        $p3x = ceil(($endX - $dist_x));
        $p3y = ceil(($endY - $dist_y));
        $p4x = ceil(($startX - $dist_x));
        $p4y = ceil(($startY - $dist_y));

        $array = array(0=>$p1x, $p1y, $p2x, $p2y, $p3x, $p3y, $p4x, $p4y);
        imagefilledpolygon($img, $array, (count($array)/2), $colour);
    }


    ########################################################
    # Functions used to send the SMS message
    ########################################################

    public static function httpRequest($url){
        $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
        preg_match($pattern,$url,$args);
        $in = "";
        $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
        if (!$fp) {
            return("$errstr ($errno)");
        } else {
            $out = "GET /$args[3] HTTP/1.1\r\n";
            $out .= "Host: $args[1]:$args[2]\r\n";
            $out .= "User-agent: Ozeki PHP client\r\n";
            $out .= "Accept: */*\r\n";
            $out .= "Connection: Close\r\n\r\n";

            fwrite($fp, $out);
            while (!feof($fp)) {
                $in.=fgets($fp, 128);
            }
        }
        fclose($fp);
        return($in);
    }



    public static function ozekiSend($phone, $msg, $debug=false){
        //test log
//        $arr['test'] = 'asfdsfa';
//        $arr['test01'] = 'HoaNX Demo';
//        self::log($arr);
//        return;

        $html_debug = array();
        $url = 'username='.Constant::OZEKI_USER;
        $url.= '&password='.Constant::OZEKI_PASSWORD;
        $url.= '&action=sendmessage';
        $url.= '&messagetype=SMS:TEXT';
        $url.= '&recipient='.urlencode($phone);
        $url.= '&messagedata='.urlencode($msg);

        $urltouse =  Constant::OZEKI_URL.$url;
        if ($debug) {
            $html_debug['Request'] = $urltouse;
        }

        //Open the URL to send the message
        $response = self::httpRequest($urltouse);
        if ($debug) {
//            $html_debug['Response'] = str_replace(array("<",">"),array("&lt;","&gt;"),$response);
            $html_debug['Response'] = $response;
            self::log($html_debug);
        }

        return($response);
    }

    public static function log($message = null){
        $logDir = dirname(__FILE__).'/../../log';
        if (!is_dir($logDir)) {
            mkdir($logDir);
        }

        $fp = fopen($logDir . '/' . date('Y-m-d') . '.log', 'a');

        if ($fp) {
            if(is_array($message)){
                fwrite($fp, sprintf("%s %s\n", date('Y-m-d H:i:s'), print_r($message, true)));
            }else{
                fwrite($fp, sprintf("%s %s\n", date('Y-m-d H:i:s'), $message));
            }
            fclose($fp);
        }
    }
/** ======================================= CONNECT LDAP SERVER  ======================================= */
    // explode DN into array
    public static function explode_dn($dn, $with_attributes=0)
    {
        $result = ldap_explode_dn($dn, $with_attributes);
        //translate hex code into ascii again
        foreach($result as $key => $value) $result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
        return $result;
    }

    // get members list from AD
    public static function get_members($group = null) {
        //to connect to LDAP
        $user="ldap_connect";
        $password="C0nn3t_Ld4P";

        //group of users
        //$group2="Intranet Users";

        if(is_null($group))
            $group=Constant::LDAP_MANAGER_GROUP;

        // Active Directory server
        $ldap_host = "172.16.15.11";

        // Active Directory DN
        $ldap_dn = "OU=gemtechlab,DC=gemtechlab,DC=ch";

        // Domain, for purposes of constructing $user
        $ldap_usr_dom = "@gemtechlab.ch";

        // connect and search ldap
        $ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
        @ldap_bind($ldap, $user . $ldap_usr_dom, $password) or die("Could not bind to LDAP");
        $results = ldap_search($ldap,$ldap_dn, "cn=" . $group);
        $entries = ldap_get_entries($ldap, $results);

        $dirty = 0;

        // build array of members for this group, first item is count - skipped using $dirty
        foreach($entries[0]['member'] as $member) {
            if($dirty == 0) {
                $dirty = 1;
            } else {
                $member_dets = self::explode_dn($member);
                $members[str_replace("CN=","",$member_dets[0])] = str_replace("CN=","",$member_dets[0]);
            }
        }

        return $members;
    }

}